import express from 'express';
import { body, validationResult } from 'express-validator';
import { RedeemCode, Domain, Expert, UserQuota, UserLog } from '../../models/index.js';
import { authenticateMobileUser } from '../../middleware/auth.js';
import { catchAsync, BusinessError } from '../../middleware/errorHandler.js';
import { success } from '../../utils/response.js';

const router = express.Router();

// 用户兑换码兑换
router.post('/redeem',
  authenticateMobileUser,
  [
    body('code')
      .notEmpty()
      .withMessage('兑换码不能为空')
      .isLength({ min: 7, max: 7 })
      .withMessage('兑换码长度必须为7位')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { code } = req.body;
    const userId = req.user.id;
    const ip = req.ip;
    const userAgent = req.get('User-Agent');
    
    // 查找兑换码
    const redeemCode = await RedeemCode.findByCode(code);
    if (!redeemCode) {
      throw new BusinessError('兑换码不存在');
    }
    
    // 检查兑换码是否可用
    if (!redeemCode.canRedeem()) {
      throw new BusinessError('兑换码已使用或已过期');
    }

    // 批次验证：检查用户是否已在该批次中兑换过兑换码
    if (redeemCode.batch) {
      const hasRedeemed = await RedeemCode.hasUserRedeemedInBatch(userId, redeemCode.batch);
      if (hasRedeemed) {
        throw new BusinessError('您已在该批次中兑换过兑换码，每个批次只能兑换一次');
      }
    }

    // 验证目标是否有效
    if (redeemCode.quota_type === 'domain' && redeemCode.target_id) {
      const domain = await Domain.findByPk(redeemCode.target_id);
      if (!domain || !domain.is_enabled) {
        throw new BusinessError('兑换码对应的领域不存在或已禁用');
      }
    } else if (redeemCode.quota_type === 'expert' && redeemCode.target_id) {
      const expert = await Expert.findByPk(redeemCode.target_id);
      if (!expert || !expert.is_enabled) {
        throw new BusinessError('兑换码对应的专家不存在或已禁用');
      }
    }
    
    // 使用兑换码
    await redeemCode.redeem(userId);
    
    // 创建用户额度
    await UserQuota.createQuota({
      user_id: userId,
      quota_type: redeemCode.quota_type,
      target_id: redeemCode.target_id,
      total_count: redeemCode.redeem_count,
      used_count: 0,
      remaining_count: redeemCode.redeem_count,
      expires_at: redeemCode.expires_at
    });
    
    // 记录兑换日志
    await UserLog.createRedeemLog(userId, redeemCode.id, ip, userAgent);
    
    res.json(success({
      quota_type: redeemCode.quota_type,
      redeem_count: redeemCode.redeem_count,
      target_name: redeemCode.domain?.name || redeemCode.expert?.nickname || '通用'
    }, '兑换成功'));
  })
);

export default router;
